/**
 * This file is part of the CAKIS project.
 * 
 * Copyright (c) 2009-2010 - Florian Arndt, Christian Kerl
 * 
 * @license GNU Lesser General Public License v3 <http://www.opensource.org/licenses/lgpl-3.0.html>
 * @since   07.05.2010
 * @version SVN: $Id: SaveProductListCommand.java 111 2010-05-07 10:50:22Z f.aarndt@web.de $
 */

package org.cakis.client.commands;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.microedition.lcdui.Command;
import javax.microedition.rms.RecordStore;

import org.cakis.client.forms.ProductListForm;
import org.cakis.webservice.ProductListEntry;

/**
 * SaveProductListCommand
 *
 * @author Florian Arndt
 */
public class SaveProductListCommand extends AbstractCommand {
	private ProductListForm form;
	private RecordStore productListStore;
	
	public SaveProductListCommand(ProductListForm form) {
		super("Speichern", Command.OK, 1);
		this.form = form;
	}

	public void execute() {
		boolean choice[] = new boolean[form.size()];
		form.getSelectedFlags(choice);
		
		ProductListEntry[] productEntries = form.getProductEntries();
		
		form.deleteAll();
		
		for (int i = 0; i < productEntries.length; i++) {
			form.append(productEntries[i].getProduct().getName() + "  x" +
					productEntries[i].getCount(), null);
		}
		form.setSelectedFlags(choice);
		
		try {
			RecordStore.deleteRecordStore("productListStore");
		} catch (Exception e1) {
			e1.printStackTrace();
		} 
		
		try {
			productListStore = RecordStore.openRecordStore("productListStore", true);
		} catch (Exception e2) {
			e2.printStackTrace();
		}
		
		for (int i = 0; i < productEntries.length; i++) {
			ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
			DataOutputStream outputStream = new DataOutputStream(byteStream);
			try {
				outputStream.writeUTF(productEntries[i].getProduct().getName());
				outputStream.write(productEntries[i].getCount().intValue());
				outputStream.writeBoolean(choice[i]);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			byte[] output = byteStream.toByteArray();
			
			try {
				productListStore.addRecord(output, 0, output.length);
			} catch (Exception e) {
				e.printStackTrace();
			}	
		}
		
		try {
			productListStore.closeRecordStore();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
